package net.zjitc.android2019.ch3storage;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import net.zjitc.android2019.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class ch3FileInner extends AppCompatActivity {
    Button btn1,btn2;
    TextView textView;
    String fileName="hello.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ch3_file_inner);

        btn1 = findViewById(R.id.ch3_file_inner_btn_write);
        btn2 = findViewById(R.id.ch3_file_inner_btn_read);
        textView = findViewById(R.id.ch3_file_inner_tv);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.ch3_file_inner_btn_write:
                        write();
                        break;
                    case R.id.ch3_file_inner_btn_read:
                        read();
                        break;
                }
            }
        };
        btn1.setOnClickListener(listener);
        btn2.setOnClickListener(listener);

    }
    private void read(){
        FileInputStream in;
        BufferedReader br;
        try {
            in=this.openFileInput(fileName);
            br=new BufferedReader(new InputStreamReader(in));
            /*字符缓冲流，一次读取一行文本*/
            String line=null;
            String s="";
            while ((line=br.readLine())!=null){
                s=s+line+"\n";
            }
            textView.setText(s);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            /*关闭流*/
        }


    }


    /**
     * 将内容写入内部文件：
     * 1.定义文件名
     * 2.定义要写入文件的内容
     * 3.利用Context提供的openFileOutput()方法得到FileOutPutStream对象
     * 4.java流的方式将数据写入到文件*/


    private void write(){
        String message="hello\nword";
        FileOutputStream out;
        BufferedWriter bw;
        try {
            out=this.openFileOutput(fileName,MODE_PRIVATE);
            /*可以直接使用基本字节流，也可以字符缓冲流*/

            bw=new BufferedWriter(new OutputStreamWriter(out));
            bw.write(message);
            bw.flush();
            Toast.makeText(this,"写入成功",Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            /*关闭流*/
        }

    }
}
